package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * <pre>
 * 考试答卷
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/examinationAnswerSheet")
public class
ExaminationAnswerSheetController extends BaseController {
    @Autowired
    private ExaminationAnswerSheetComService examinationAnswerSheetService;
    @Autowired
    private ExaminationPaperService examinationPaperService;
    @Autowired
    private StuSignUpComService stuSignUpService;
    @Autowired
    private ExaminationQuestionsService examinationQuestionsService;
    @Autowired
    private ExaminationBatchService examinationBatchService;

    @GetMapping()
    @RequiresPermissions("jzweb:examinationAnswerSheet:examinationAnswerSheet")
    String ExaminationAnswerSheet() {
        return "jzweb/examinationAnswerSheet/examinationAnswerSheet";
    }

    /**
     * 考试答卷
     * @param req
     * @param examinationAnswerSheetDTO
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:examinationAnswerSheet:examinationAnswerSheet")
    public Result<Page<ExaminationAnswerSheetComDO>> list(HttpServletRequest req ,ExaminationAnswerSheetDO examinationAnswerSheetDTO, int pageNumber, int pageSize) {
        //查询用户角色
        String roleName = getRoleNames();
        /*if (!roleName.contains("超级用户角色")&&!roleName.contains("竞赛超级管理员")) {
            Page<ExaminationAnswerSheetComDO> page= null;
            Object orgId = req.getSession().getAttribute("orgId");
            if (orgId != null){
                page = examinationAnswerSheetService.findList(Long.parseLong(orgId.toString()), pageNumber, pageSize);
            }else {
                page = examinationAnswerSheetService.findList(this.getUser().getOrgId(), pageNumber, pageSize);
            }

            List<ExaminationAnswerSheetComDO> list = page.getRecords();
            if (list.size() != 0) {
                for (ExaminationAnswerSheetComDO examinationAnswerSheet : list) {

                    if (examinationAnswerSheet != null) {
                        if (examinationAnswerSheet.getEpaperId() != null) {
                            ExaminationPaperDO examinationPaperDO = examinationPaperService.selectById(examinationAnswerSheet.getEpaperId());
                            if (examinationPaperDO != null) {
                                examinationAnswerSheet.setEpaperName(examinationPaperDO.getName());
                            }
                        }

                        if (examinationAnswerSheet.getStuSignId() != null) {
                            StuSignUpComDO stuSignUpDO = stuSignUpService.selectById(examinationAnswerSheet.getStuSignId());
                            if (stuSignUpDO != null) {
                                examinationAnswerSheet.setStuName(stuSignUpDO.getName());
                                ExaminationBatchDO examinationBatchDO= examinationBatchService.selectById(stuSignUpDO.getCbatchId());
                                examinationAnswerSheet.setBatchName(examinationBatchDO.getName());
                                examinationAnswerSheet.setNum2(stuSignUpDO.getNum2());
                            }
                        }
                    }
                }
            }
            page.setRecords(list).setTotal(list.size());
            return Result.ok(page);
        } else {*/
            Wrapper<ExaminationAnswerSheetComDO> wrapper = new EntityWrapper<ExaminationAnswerSheetComDO>().orderBy("id", false);
            if (examinationAnswerSheetDTO.getState() != null){
                wrapper.eq("state",examinationAnswerSheetDTO.getState());
            }
            if (StringUtils.isNotBlank(examinationAnswerSheetDTO.getEpaperName())){
                Wrapper<ExaminationPaperDO> exWrapper = new EntityWrapper<ExaminationPaperDO>().like("name",examinationAnswerSheetDTO.getEpaperName());
                List<ExaminationPaperDO>  examinationPaperDOS = examinationPaperService.selectList(exWrapper);
                String str = "";
                for (ExaminationPaperDO examinationPaperDO : examinationPaperDOS){
                    str = str + examinationPaperDO.getId() + ",";
                }
                wrapper.and();
                if(StringUtils.isNotBlank(str)){
                    wrapper.in("epaper_id",str.substring(0,str.length()-1));
                }else{
                    wrapper.eq("epaper_id",null);
                }
            }
            if (StringUtils.isNotBlank(examinationAnswerSheetDTO.getStuName())){
                Wrapper<StuSignUpComDO> stuWrapper = new EntityWrapper<StuSignUpComDO>().like("name",examinationAnswerSheetDTO.getStuName());
                List<StuSignUpComDO>  stuSignUpDOS = stuSignUpService.selectList(stuWrapper);
                String str = "";
                for (StuSignUpComDO stuSignUpDO : stuSignUpDOS){
                    str = str + stuSignUpDO.getId() + ",";
                }
                wrapper.and();
                if(StringUtils.isNotBlank(str)){
                    wrapper.in("stu_sign_id",str.substring(0,str.length()-1));
                }else{
                    wrapper.eq("stu_sign_id",null);
                }
            }

            Page<ExaminationAnswerSheetComDO> page = examinationAnswerSheetService.selectPage(getPage(ExaminationAnswerSheetComDO.class), wrapper);
            List list = new ArrayList();
            for (int i = 0; i < page.getRecords().size(); i++) {
                ExaminationAnswerSheetComDO obj = (ExaminationAnswerSheetComDO) page.getRecords().get(i);
                if (obj.getEpaperId() != null) {
                    ExaminationPaperDO examinationPaperDO = examinationPaperService.selectById(obj.getEpaperId());
                    if (examinationPaperDO != null) {
                        obj.setEpaperName(examinationPaperDO.getName());
                    }
                }
                if (obj.getStuSignId() != null) {
                    StuSignUpComDO stuSignUpDO = stuSignUpService.selectById(obj.getStuSignId());
                    if (stuSignUpDO != null) {
                        obj.setStuName(stuSignUpDO.getName());
                        obj.setNum2(stuSignUpDO.getNum2());
                        ExaminationBatchDO examinationBatchDO= examinationBatchService.selectById(stuSignUpDO.getCbatchId());
                        if(examinationBatchDO!=null){
                            obj.setBatchName(examinationBatchDO.getName());
                        }

                    }

                }
                list.add(obj);
            }
            page.setRecords(list);
            return Result.ok(page);
        }
   // }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:examinationAnswerSheet:add")
    String add() {
        return "jzweb/examinationAnswerSheet/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:examinationAnswerSheet:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        ExaminationAnswerSheetComDO examinationAnswerSheet = examinationAnswerSheetService.selectById(id);
        model.addAttribute("examinationAnswerSheet", examinationAnswerSheet);
        return "jzweb/examinationAnswerSheet/edit";
    }

    @GetMapping("/info/{id}")
    @RequiresPermissions("jzweb:examinationAnswerSheet:examinationAnswerSheet")
    String info(@PathVariable("id") Long id, Model model) {
        ExaminationAnswerSheetComDO examinationAnswerSheet = examinationAnswerSheetService.selectById(id);
        if (examinationAnswerSheet.getEpaperId() != null) {
            ExaminationPaperDO examinationPaperDO = examinationPaperService.selectById(examinationAnswerSheet.getEpaperId());
            if (examinationPaperDO != null) {
                examinationAnswerSheet.setEpaperName(examinationPaperDO.getName());
            }
        }
        if (examinationAnswerSheet.getStuSignId() != null) {
            StuSignUpComDO stuSignUpDO = stuSignUpService.selectById(examinationAnswerSheet.getStuSignId());
            if (stuSignUpDO != null) {
                examinationAnswerSheet.setStuName(stuSignUpDO.getName());
            }
        }
        List<Map> maps = new ArrayList<>();
        BigDecimal results = new BigDecimal(0);
        String[] ssr = examinationAnswerSheet.getAnswerList().split("\\{\"id\":\"");
        for (int i = 1; i < ssr.length; i++) {
            Map map = new HashMap();
            String[] ssc = ssr[i].split("\"}");
            for (int j = 0; j < ssc.length; j++) {
                String[] ssa = ssc[j].split("\",\"value\":\"");

                if (ssa.length > 1) {
                    String ssas1 = ssa[1].substring(0, ssa[1].length() - 11);
                    ExaminationQuestionsDO examinationQuestionsDO = examinationQuestionsService.selectById(ssa[0]);
                    if (null != examinationQuestionsDO) {
                        map.put("titleNumber", examinationQuestionsDO.getTitleNumber());//题号
                        map.put("introduce", examinationQuestionsDO.getIntroduce());//题目内容
                        map.put("titleOptions", examinationQuestionsDO.getOptions());//题目选项
                        if (examinationQuestionsDO.getType() == 0 || examinationQuestionsDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
                            if (examinationQuestionsDO.getAnswers().equals(ssas1)) {
                                map.put("answers", examinationQuestionsDO.getAnswers());//正确答案
                                map.put("options", ssas1);//考生选项
                                map.put("yesOrNo", "是");
                                results = results.add(BigDecimal.valueOf(examinationQuestionsDO.getScore()));
                            } else {
                                map.put("answers", examinationQuestionsDO.getAnswers());//正确答案
                                map.put("options", ssas1);//考生选项
                                map.put("yesOrNo", "否");
                            }
                        } else if (examinationQuestionsDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案

                            boolean isRight = true;
                            if (ssa[1] == null || ssa[1] == "") {
                                isRight = false;
                            } else {
                                String[] ssb = ssa[1].substring(0, ssa[1].length() - 11).split(";;");
                                String answer = examinationQuestionsDO.getAnswers();
                                if (ssb.length != answer.split(";;").length) {
                                    isRight = false;
                                } else {
                                    for (int n = 0; n < ssb.length; n++) {
                                        //if (ssb[n].equals("A") || ssb[n].equals("B") || ssb[n].equals("C") || ssb[n].equals("D") || ssb[n].equals("E") || ssb[n].equals("F")) {
                                        if (!answer.contains(ssb[n]) || ssb[n].equals("")) {
                                            isRight = false;
                                            break;
                                        }

                                    }
                                }
                            }

                            if (isRight) {
                                map.put("answers", examinationQuestionsDO.getAnswers());//正确答案
                                map.put("options", ssas1);//考生选项
                                map.put("yesOrNo", "是");
                                results = results.add(BigDecimal.valueOf(examinationQuestionsDO.getScore()));
                            } else {
                                map.put("answers", examinationQuestionsDO.getAnswers());//正确答案
                                map.put("options", ssas1);//考生选项
                                map.put("yesOrNo", "否");
                            }
                        }
                        //把案例分析剔除出去
                        if (map.containsKey("answers")) {
                            maps.add(map);
                        }
                    }
                        //  maps.add(map);
                    } else if (ssa.length == 1 && !ssa[0].equals(",") && !ssa[0].equals("]")) {
                        ExaminationQuestionsDO examinationQuestionsDO = examinationQuestionsService.selectById(ssa[0]);
                        if(null!=examinationQuestionsDO){
                            map.put("titleNumber", examinationQuestionsDO.getTitleNumber());//题号
                            map.put("introduce", examinationQuestionsDO.getIntroduce());//题目内容
                            map.put("titleOptions", examinationQuestionsDO.getOptions());//题目选项
                            map.put("answers", examinationQuestionsDO.getAnswers());//正确答案
                            map.put("options", "");//考生选项
                            map.put("yesOrNo", "否");

                            maps.add(map);
                    }
                }
            }
        }
        examinationAnswerSheet.setAnswerLists(maps);
        examinationAnswerSheet.setScore(results.doubleValue());
        model.addAttribute("examinationAnswerSheet", examinationAnswerSheet);
        return "jzweb/examinationAnswerSheet/info";
    }


    @Log("添加考试答卷")
    @ResponseBody
    @PostMapping("/save")

    @RequiresPermissions("jzweb:examinationAnswerSheet:add")
    public Result<String> save(ExaminationAnswerSheetComDO examinationAnswerSheet) {
        // examinationBatchService.selTimeAll();
        examinationAnswerSheetService.insert(examinationAnswerSheet);
        return Result.ok();
    }


    @Log("修改考试答卷")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:examinationAnswerSheet:edit")
    public Result<String> update(ExaminationAnswerSheetComDO examinationAnswerSheet) {
        boolean update = examinationAnswerSheetService.updateById(examinationAnswerSheet);
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除考试答卷")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:examinationAnswerSheet:remove")
    public Result<String> remove(Long id) {
        examinationAnswerSheetService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除考试答卷")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:examinationAnswerSheet:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        examinationAnswerSheetService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

}
